<?php


/**
* Модуль веб-голосования.
*
* @author Владислав В. Костянецкий <bytecoded@gmail.com>
* @link   http://drfreddy.ru/akinoyume/
*/


$titles[] = 'Голосование';

// Получилось опознать билет?

$ticket_id = get_current_ticket_id();

if ( ! $ticket_id )
{
  // Не получилось.

  $message = '';

  // Определяем, была ли попытка отправить форму входа.

  if ( count( $_POST ) )
  {  
    $number1 = filter_input( INPUT_POST , 'number1' , FILTER_SANITIZE_STRING );
    $number2 = filter_input( INPUT_POST , 'number2' , FILTER_SANITIZE_STRING );
   
    if ( ! $number1 and ! $number2 )
    {
      $message = 'Нужно ввести номер билета!';
    }
    else if ( ! $number1 or ! $number2 )
    {
      $message = 'Нужно ввести обе части номера!';
    }
    else
    {    
      $ticket = app::$db->get(
        "SELECT `id` FROM `tickets` WHERE `number` = ? AND `active` = '1' LIMIT 1",
        array( $number1 . '-' . $number2 )
      );

      if ( $ticket )
      {
        setcookie( "ticket_id"   , $ticket['id']   , time() + 60 * 60 * 24 * 30, '/' );
        setcookie( "ticket_hash" , md5( $number1 . '-' . $number2 . SECRET ) , time() + 60 * 60 * 24 * 30, '/' );

        redirect( URL . 'vote' );        
      }
       
      app::$db->execute( 
        "INSERT INTO `faults` ( `code`, `ip`, `ticket` ) VALUES ( :code, :ip, 1 )",
        array( 'code' => $number1 . '-' . $number2, 'ip' => $_SERVER['REMOTE_ADDR'] ) 
      );      
       
      $message = 'Неверный номер билета!';
    }
  }
    
  require_once HTML . 'vote/header.php';
  require_once HTML . 'vote/cases/login.php';
  require_once HTML . 'vote/footer.php';    
}
else
{
  if ( isset( $_POST['logout'] ) )
  {
    setcookie( 'ticket_id'   , 0, 0, '/' );
    setcookie( 'ticket_hash' , 0, 0, '/' );

    redirect( URL . 'vote' );
  }

  $ticket = app::$db->get( "SELECT `number`, `phone` FROM `tickets` WHERE `id` = ? AND `active` = '1' LIMIT 1", array( $ticket_id ) );
  
  $topics = app::$db->grab( "SELECT `id`, `card`, `title` FROM topics WHERE `voting_public_enabled` = 1 ORDER BY ord ASC", array(), 'id' );

  $votes = app::$db->grab( "
    SELECT t.`title` AS 'topic_title', t.card, r.voting_number , r.`voting_title` AS `title`, v.`type`
    FROM `votes` v
    INNER JOIN `requests` r ON r.`id` = v.`request_id`
    INNER JOIN `topics` t ON t.`id` = r.`topic_id`
    WHERE v.`ticket_id` = ?    
    ORDER BY v.`id` DESC",
    array( $ticket_id )
  );
  
  if ( isset( $key[1] ) )
  {
    $topic_code  = intval( $key[1] );  
    $topic   = app::$db->get( "SELECT `id`, `card`, `title` FROM topics WHERE `code` = ? AND `voting_public_enabled` = 1", array( $topic_code ) );  

    if ( ! $topic ) redirect( URL . 'vote' );
    
    $topic_id = $topic['id'];
  
    $requests = app::$db->grab( "
      SELECT `voting_number` AS 'number', `voting_title` AS 'title'
      FROM `requests`
      WHERE `topic_id` = ? AND `voting_number` <> 0 AND `voting_title` <> ''
      ORDER BY `voting_number` ASC",
      array( $topic_id )
    );
    
    if ( isset( $key[2] ) )
    {
      $request_number = intval( $key[2] );
    
      $request = app::$db->get( "
        SELECT `id` FROM `requests` 
        WHERE `voting_number` = :voting_number AND `topic_id` = :topic_id
        LIMIT 1",
        array(
          'voting_number' => $request_number,
          'topic_id'      => $topic_id,
        )
      );
      
      if ( $request )
      {    
        app::$db->execute(
          "DELETE FROM `votes` WHERE `ticket_id` = :ticket_id AND `topic_id` = :topic_id",
          array( 'ticket_id' => $ticket_id, 'topic_id' => $topic_id )
        );    
 
        app::$db->execute( 
          
          "INSERT INTO `sms`
            ( `ticket_id`, `sender`, `message`, `sent_time`, `recieve_time`, `web`, `type`, `result` ) 
            VALUES 
            ( :ticket_id, :sender, :message, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 1, 'vote', :result )",
            
          array( 
            'ticket_id'     => $ticket_id,
            'sender'        => $_SERVER['REMOTE_ADDR'],
            'message'       => $topic_id . ' ' . $request_number,
            'result'        => $topic_id . ' = ' . $request['id'],
          ) 
          
        );
 
        app::$db->execute( "
          INSERT INTO `votes`
          ( `type`, `ticket_id`, `topic_id`, `request_id` )
          VALUES
          ( 'web', :ticket_id, :topic_id, :request_id )",
              
          array(      
            'ticket_id'     => $ticket_id,
            'topic_id'      => $topic_id,
            'request_id'    => $request['id'],
          )
        );
        
        redirect( URL . 'vote' );
      }
    }
  }
  
  require_once HTML . 'vote/header.php';
  require_once HTML . 'vote/cases/page.php';
  require_once HTML . 'vote/footer.php';    
}

exit;

function get_current_ticket_id()
{
  $id   = filter_input( INPUT_COOKIE, 'ticket_id'   , FILTER_VALIDATE_INT    );
  $hash = filter_input( INPUT_COOKIE, 'ticket_hash' , FILTER_SANITIZE_STRING );

  if ( ! $id or ! $hash ) return 0;

  $ticket = app::$db->get( "SELECT `number` FROM `tickets` WHERE `id` = ? AND `active` = '1' LIMIT 1", array( $id ) );
  
  if ( ! $ticket ) return 0;
       
  if ( $hash != md5( $ticket['number'] . SECRET ) ) return 0;
  
  return $id;
}